CODE 119. Integer to Roman

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/10/2013-11-10-CODE 119 Integer to Roman/

访问原文「CODE 119. Integer to Roman

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
static List<R2A> r2a = new ArrayList<R2A>();
static {
r2a.add(new R2A(1000, 'M'));
r2a.add(new R2A(500, 'D'));
r2a.add(new R2A(100, 'C'));
r2a.add(new R2A(50, 'L'));
r2a.add(new R2A(10, 'X'));
r2a.add(new R2A(5, 'V'));
r2a.add(new R2A(1, 'I'));
}
public String intToRoman(int num) {
// Start typing your Java solution below
// DO NOT write main() function
int number = num;
StringBuilder sb = new StringBuilder();
while (number > 0) {
for (int i = 0; i < r2a.size(); i++) {
int jieguo = number / r2a.get(i).number;
if (jieguo <= 0) {
continue;
} else {
if (jieguo == 4) {
sb.append(r2a.get(i).roman);
sb.append(r2a.get(i - 1).roman);
number = number % r2a.get(i).number;
} else {
if (i % 2 == 1
&& jieguo == 1
&& i < r2a.size() - 1
&& number % r2a.get(i).number
/ r2a.get(i + 1).number == 4) {
sb.append(r2a.get(i + 1).roman);
sb.append(r2a.get(i - 1).roman);
number = number % r2a.get(i + 1).number;
} else {
for (int j = 0; j < jieguo; j++) {
sb.append(r2a.get(i).roman);
}
number = number % r2a.get(i).number;
}
}
break;
}
}
}
return sb.toString();
}
static class R2A {
public int number;
public char roman;
R2A(int n, char r) {
number = n;
roman = r;
}
}
Jerky Lu wechat
欢迎加入微信公众号